package com.yixia.framework.dataScope.handle;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;

import com.yixia.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 对通用数据进行自动填充
 *
 * @author: yimeng
 */

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {


    final static private String OPER_TIME = "operTime";
    final static private String CREATE_TIME = "createTime";
    final static private String UPDATE_TIME = "updateTime";
    final static private String CREATE_BY = "createBy";
    final static private String UPDATE_BY = "updateBy";
    final static private String CREATE_BY_ID = "createById";
    final static private String LOGIN_TIME = "loginTime";

    /**
     * 当mybatis-plus进行添加操作时自动填充的字段
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.hasSetter(CREATE_TIME)) {
            metaObject.setValue(CREATE_TIME, new Date());
        }
        if (metaObject.hasSetter(UPDATE_TIME)) {
            metaObject.setValue(UPDATE_TIME, new Date());
        }
        if (metaObject.hasSetter(CREATE_BY)) {
            metaObject.setValue(CREATE_BY,  SecurityUtils.getLoginUser().getUser().getUsername());
        }
        if (metaObject.hasSetter(UPDATE_BY)) {
            metaObject.setValue(UPDATE_BY, SecurityUtils.getLoginUser().getUser().getUsername());
        }
        if (metaObject.hasSetter(CREATE_BY_ID)) {
            metaObject.setValue(CREATE_BY_ID, SecurityUtils.getLoginUser().getUser().getUserId());
        }
        if (metaObject.hasSetter(OPER_TIME)) {
            metaObject.setValue(OPER_TIME, new Date());
        }
        if (metaObject.hasSetter(LOGIN_TIME)) {
            metaObject.setValue(LOGIN_TIME, new Date());
        }
    }

    /**
     * 当mybatis-plus进行修改操作时自动填充的字段
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasSetter(UPDATE_TIME)) {
            metaObject.setValue(UPDATE_TIME, new Date());
        }
        if (metaObject.hasSetter(UPDATE_BY)) {
            metaObject.setValue(UPDATE_BY, SecurityUtils.getLoginUser().getUser().getUsername());
        }
    }
}
